package com.ibeetl.cms.service;


import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.service.CoreBaseService;
import com.ibeetl.admin.core.service.CoreDictService;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.cms.dao.CmsArticleTagDao;
import com.ibeetl.cms.entity.CmsArticleTag;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.List;






/**
 * CmsArticleTag Service
 */

@Service
@Transactional
public class CmsArticleTagService extends CoreBaseService<CmsArticleTag>{

    @Autowired private CmsArticleTagDao cmsArticleTagDao;
    @Autowired
    CoreDictService dictService;
    public PageQuery<CmsArticleTag>queryByCondition(PageQuery query){
        PageQuery ret =  cmsArticleTagDao.queryByCondition(query);
        queryListAfter(ret.getList());
        return ret;
    }

    public void batchDelCmsArticleTag(List<Long> ids){
        try {
            cmsArticleTagDao.batchDelCmsArticleTagByIds(ids);
        } catch (Exception e) {
            throw new PlatformException("批量删除CmsArticleTag失败", e);
        }
    }

    public List<Long> getDictIdByArticleId(Long articleId) {
        List<Long> l = this.cmsArticleTagDao.getDictIdByArticleId(articleId);
        return l;
    }
    public List<Long> getDictIdByArticleId(String articleId) {
        return this.getDictIdByArticleId(NumberUtils.toLong(articleId));
    }
    public boolean existTagForArticle(String tagName, Long articleId, String dictType) {
        List<CoreDict> dictList = dictService.findAllByType(dictType);
        List<Long> articleTagIdList = getDictIdByArticleId(articleId);
        boolean exist = false;
        for (Iterator<CoreDict> iterator = dictList.iterator(); iterator.hasNext(); ) {
            CoreDict dict =  iterator.next();
            //当前文章所包含的标签，包含了当前标签，并且需要判断的标签名称或值等于当前标签
            if (articleTagIdList.contains(dict.getId()) && (StringUtils.equals(tagName,dict.getName()) || StringUtils.equals(tagName,dict.getValue()))) {
                exist = true;
                break;
            }
        }
        return exist;
    }
}